package com.white.hot.service.impl;


import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.white.hot.dao.UserDao;
import com.white.hot.dto.User;
import com.white.hot.service.UserService;
import com.white.hot.utils.MD5Util;

@Service("userService")
public class UserServiceImpl implements UserService
{
	@Resource
	private UserDao userDao;

	public User getUserById(long id)
	{
		return userDao.selectByPrimaryKey(id);
	}

	@Override
	public void addUser(User user)
	{
		userDao.insert(user);
	}

	@Override
	public User findUserByTel(String tel)
	{
		return userDao.selectByPhone(tel);
	}

	@Override
	public User login(String account, String pwd)
	{
		User u = userDao.selectByAccount(account, pwd);
		if(u != null)
		{
			u.setToken(generateToken(u.getSuId()));
			userDao.updateByPrimaryKey(u);
			return u;			
		}
		return null;
	}
	
	public String generateToken(Object obj)
	{
		int hash = obj.hashCode();
		String timestamp = getTimeString();
		return MD5Util.MD5Encode(timestamp+hash, "UTF-8");
	}
	
	private SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDhhmmssSSS");
	public String getTimeString()
	{
		return sdf.format(new Date());
	}

	@Override
	public void update(User u)
	{
		userDao.updateByPrimaryKey(u);
	}
}
